package com.ruoyi.web.controller.store.pan;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.mapper.ApproveMapper;
import com.ruoyi.system.mapper.ApproveMissionMapper;
import com.ruoyi.system.service.ApproveService;
import com.ruoyi.system.service.IStorePanDetailService;
import com.ruoyi.system.service.IStorePanService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 盘点Controller
 *
 * @author wlmes
 * @date 2023-11-23
 */
@RestController
@RequestMapping("/system/pan")
@Api(tags = "盘点相关接口")
public class StorePanController extends BaseController {
    @Autowired
    private IStorePanService storePanService;

    @Autowired
    private ISysUserService sysUserService;

    @Resource
    ApproveService approveService;

    @Resource
    ApproveMapper approveMapper;

    @Resource
    ApproveMissionMapper approveMissionMapper;

    @Resource
    IStorePanDetailService storePanDetailService;

    @GetMapping("/getAllApprovalList")
    @ApiOperation("获取当前登录人科室的所有人")
    public AjaxResult getAllApprovalList(StorePan storePan) {
        List<SysUser> sysUsers = sysUserService.getAllApprovalList(SecurityUtils.getUserId());
        return AjaxResult.success(sysUsers);
    }

    /**
     * 查询盘点列表
     */
    @GetMapping("/list")
    @ApiOperation("查询盘点列表")
    public TableDataInfo list(StorePan storePan) {
//        SysUser user = SecurityUtils.getLoginUser().getUser();
//        String area = user.getLocation();
//        if (area.equals("二区")) {
//            storePan.setArea(area);
//        } else if (area.equals("一区")) {
//            storePan.setArea(area);
//        } else {
//            storePan.setArea("");
//        }
        startPage();
        List<StorePan> list = storePanService.selectStorePanList(storePan);
        return getDataTable(list);
    }

    /**
     * 导出盘点列表
     */
//    @PreAuthorize("@ss.hasPermi('system:pan:export')")
    @Log(title = "盘点", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ApiOperation("导出盘点列表")
    public AjaxResult export(StorePan storePan) {
        List<StorePan> list = storePanService.selectStorePanList(storePan);
        ExcelUtil<StorePan> util = new ExcelUtil<StorePan>(StorePan.class);
        return util.exportExcel(list, "pan");
    }

    /**
     * 获取盘点详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:pan:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation("获取盘点详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        StorePan storePan = storePanService.selectStorePanById(id);

        StorePanDetail storePanDetail = new StorePanDetail();
        storePanDetail.setPanNum(storePan.getPanNum());
        List<StorePanDetail> list = storePanDetailService.selectStorePanDetailList(storePanDetail);

        storePan.setStorePanDetailList(list);
        return AjaxResult.success(storePan);
    }

    //盘点-获取当前库存明细
    @GetMapping(value = "/getStoreDetailList")
    @ApiOperation("获取要盘点的表头和明细")
    public AjaxResult getStoreDetailList(StorePan storePan) {
        return AjaxResult.success(storePanService.getStoreDetailList(storePan));
    }

    /**
     * 新增盘点
     */
//    @PreAuthorize("@ss.hasPermi('system:pan:add')")
    @Log(title = "盘点", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增盘点")
    @RepeatSubmit
    public AjaxResult add(@RequestBody StorePan storePan) {
        return toAjax(storePanService.insertStorePan(storePan));
    }

    @Log(title = "新增库存盘点单据", businessType = BusinessType.INSERT)
    @PostMapping("/saveNewStorePan")
    @ApiOperation("新增库存盘点单据")
    @RepeatSubmit
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult saveNewStorePan(@RequestBody StorePan storePan) {
        storePanService.saveNewStorePan(storePan);
        return AjaxResult.success();
    }

    @PostMapping("/confirmStorePan")
    @ApiOperation("盘点发起审批")
    @RepeatSubmit
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult confirmStorePan(@RequestBody StorePan storePan) {
        storePanService.confirmStorePan(storePan);
        return AjaxResult.success();
    }

    @Log(title = "盘点审核通过", businessType = BusinessType.INSERT)
    @PostMapping("/approvePassStorePan")
    @ApiOperation("盘点审核通过")
    @RepeatSubmit
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult approvePassStorePan(@RequestBody StorePan storePan) {
        storePanService.approvePassStorePan(storePan.getId());
        return AjaxResult.success();
    }

    @Log(title = "库管重新盘点提交", businessType = BusinessType.INSERT)
    @PostMapping("/del")
    @ApiOperation("库管重新盘点提交")
    @RepeatSubmit
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult del(@RequestBody StorePan storePan) {
        //删除后新增
        storePanService.deleteStorePanById(storePan.getId());
        for (StorePanDetail storePanDetail : storePan.getStorePanDetailList()) {
            storePanDetailService.deleteStorePanDetailById(storePanDetail.getId());
        }
        //新增
        storePanService.saveNewStorePan(storePan);
        return AjaxResult.success();
    }


    /**
     * 修改盘点
     */
//    @PreAuthorize("@ss.hasPermi('system:pan:edit')")
    @Log(title = "盘点", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改盘点")
    @RepeatSubmit
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult edit(@RequestBody StorePan storePan) {
        if (null != storePan.getApprovalUserId()) {
            ApproveMission query = new ApproveMission();
            query.setActivityId(storePan.getId());
            query.setActivityType("盘点审批");
            List<ApproveMission> approveMissions = approveMissionMapper.selectApproveMissionList(query);
            if (!CollectionUtils.isEmpty(approveMissions)){
                ApproveMission approveMission = approveMissions.get(0);
                List<Approve> approvas = approveService.getByMissionId(approveMission.getId());
                if (!CollectionUtils.isEmpty(approvas)){
                    for (Approve approva : approvas) {
                        approva.setApprover(storePan.getApprovalUserId());
                        approveMapper.updateApprove(approva);
                    }
                }
            }

        }
        return toAjax(storePanService.updateStorePan(storePan));
    }

    /**
     * 删除盘点
     */
//    @PreAuthorize("@ss.hasPermi('system:pan:remove')")
    @Log(title = "盘点", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation("删除盘点")
    @RepeatSubmit
    public AjaxResult remove(@PathVariable Long[] ids) {
        for (Long id : ids) {
            StorePan storePan = storePanService.selectStorePanById(id);
            if (storePan != null) {
                if (StringUtils.isNotBlank(storePan.getApprovalState()) && storePan.getApprovalState().equals("2")) {
                    throw new BaseException("盘点单已审核通过,无法修改" + storePan.getPanNum());
                }
                storePanService.deleteStorePanById(id);
                StorePanDetail query = new StorePanDetail();
                query.setPanNum(storePan.getPanNum());
                List<StorePanDetail> storePanDetailList = storePanDetailService.selectStorePanDetailList(query);
                if (!CollectionUtils.isEmpty(storePanDetailList)) {
                    for (StorePanDetail storePanDetail : storePanDetailList) {
                        storePanDetailService.deleteStorePanDetailById(storePanDetail.getId());
                    }
                }
            }
        }
        return AjaxResult.success();
    }
}
